package com.yc.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.R_Code;
import com.yc.Result;
import com.yc.entities.BloodSugarDepartment;
import com.yc.entities.BloodSugarDoctor;
import com.yc.entities.BloodSugarPermission;
import com.yc.entities.BloodSugarUserPermissionDepartment;
import com.yc.service.BloodSugarDepartmentService;
import com.yc.service.BloodSugarDoctorService;
import com.yc.service.BloodSugarPermissionService;
import com.yc.service.BloodSugarUserPermissionDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 科室表 前端控制器
 * </p>
 *
 * @author kuakha
 * @since 2021-04-07
 */
@RestController
@Slf4j
@RequestMapping("/bloodSugarDepartment")
@Api(value = "BloodSugarDepartmentController", tags = {"科室信息管理"})
public class BloodSugarDepartmentController {

    @Autowired
    private BloodSugarDepartmentService bloodSugarDepartmentService;
    @Autowired
    private BloodSugarDoctorService bloodSugarDoctorService;
    @Autowired
    private BloodSugarUserPermissionDepartmentService bloodSugarUserPermissionDepartmentService;
    @Autowired
    private BloodSugarPermissionService bloodSugarPermissionService;

    @ApiOperation(value = "pc添加科室信息")
    @PreAuthorize("hasAnyAuthority('sys:departmentManage','sys:noAccess')")
    @PostMapping("addDepartment")
    public Result addDepartment(@Valid @RequestBody BloodSugarDepartment bloodSugarDepartment) {
        LambdaQueryWrapper<BloodSugarDepartment> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(BloodSugarDepartment::getDepartmentName,bloodSugarDepartment.getDepartmentName())
                .eq(BloodSugarDepartment::getDeanId,bloodSugarDepartment.getDeanId());
        List<BloodSugarDepartment> list1 = bloodSugarDepartmentService.list(lambdaQueryWrapper);
        if (list1.size() > 0) {
            return Result.error().message("已经存在该科室");
        }
        int status = bloodSugarDepartmentService.saveDepartment(bloodSugarDepartment);
//        boolean save = bloodSugarDepartmentService.save(bloodSugarDepartment);
        if (status > 0) {
            LambdaQueryWrapper<BloodSugarPermission> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(BloodSugarPermission::getDeanId,bloodSugarDepartment.getDeanId());
            List<BloodSugarPermission> list = bloodSugarPermissionService.list(wrapper);
            List<BloodSugarUserPermissionDepartment> bloodSugarUserPermissionDepartments = new ArrayList<>();
            list.forEach(f1->{
                BloodSugarUserPermissionDepartment bloodSugarUserPermissionDepartment = new BloodSugarUserPermissionDepartment();
                bloodSugarUserPermissionDepartment.setUserId(bloodSugarDepartment.getDeanId())
                        .setDepartmentId(bloodSugarDepartment.getId())
                        .setPermissionId(f1.getId());
                bloodSugarUserPermissionDepartments.add(bloodSugarUserPermissionDepartment);
            });
            bloodSugarUserPermissionDepartmentService.saveBatch(bloodSugarUserPermissionDepartments);
            return Result.ok();
        } else {
            return Result.error().code(R_Code.R_ADD_FAIL);
        }
    }

    @ApiOperation(value = "pc修改科室信息")
    @PreAuthorize("hasAnyAuthority('sys:departmentManage','sys:noAccess')")
    @GetMapping("updateDepartment/{deanId}/{departmentName}/{id}")
    public Result updateDepartment(@ApiParam(name = "deanId", value = "院长id") @PathVariable String deanId,
                                   @ApiParam(name = "departmentName", value = "科室名称") @PathVariable String departmentName,
                                   @ApiParam(name = "id", value = "科室id") @NotNull(message = "科室id不能为空") @PathVariable Integer id) {
        LambdaQueryWrapper<BloodSugarDepartment> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(BloodSugarDepartment::getDeanId,deanId)
                .eq(BloodSugarDepartment::getDepartmentName,departmentName);
        List<BloodSugarDepartment> list1 = bloodSugarDepartmentService.list(lambdaQueryWrapper);
        if (list1.size() > 0) {
            return Result.error().message("已经存在该科室");
        }
        LambdaUpdateWrapper<BloodSugarDepartment> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(BloodSugarDepartment::getId, id).set(BloodSugarDepartment::getDepartmentName, departmentName)
                .set(BloodSugarDepartment::getUpdateTime, LocalDateTime.now());
        boolean update = bloodSugarDepartmentService.update(lambdaUpdateWrapper);
        if (update) {
            return Result.ok();
        } else {
            return Result.error().code(R_Code.R_UPDATE_FAIL);
        }
    }

    @ApiOperation(value = "pc查询科室信息")
    @PreAuthorize("hasAnyAuthority('sys:departmentManage','sys:noAccess')")
    @GetMapping(value = {"getDepartment"})
    public Result getDepartment(@ApiParam(name = "deanId", value = "院长id") @NotNull(message = "院长id不能为空") @RequestParam Integer deanId,
                                @ApiParam(name = "departmentName", value = "科室名称") @RequestParam(required = false) String departmentName,
                                @ApiParam(name = "current", value = "当前页码") @RequestParam(required = false) Integer current,
                                @ApiParam(name = "size", value = "一页显示多少条") @RequestParam(required = false) Integer size) {
        LambdaQueryWrapper<BloodSugarDepartment> bdaQueryWra = Wrappers.lambdaQuery();
        bdaQueryWra.eq(BloodSugarDepartment::getDeanId, deanId);
        if (StringUtils.isNotBlank(departmentName)) {
            bdaQueryWra.like(BloodSugarDepartment::getDepartmentName, departmentName);
        }
        Page<BloodSugarDepartment> departmentPage = new Page<>(current == null ? 0 : current, size == null ? 10 : size);
        IPage<BloodSugarDepartment> sugarDepartmentPage = bloodSugarDepartmentService.page(departmentPage, bdaQueryWra);
        if (departmentPage.getTotal() > 0) {
            return Result.ok().data(sugarDepartmentPage.getRecords()).total((int) departmentPage.getTotal());
        } else {
            return Result.ok().code(R_Code.R_NULL_DATA_FAIL);
        }
    }

    @ApiOperation(value = "pc删除科室信息")
    @PreAuthorize("hasAnyAuthority('sys:departmentManage','sys:noAccess')")
    @GetMapping("deleteDepartment/{id}")
    public Result deleteDepartment(@ApiParam(name = "id", value = "科室id") @NotNull(message = "科室id不能为空") @PathVariable Integer id) {
        boolean deleted = bloodSugarDepartmentService.removeById(id);
        if (deleted) {
            LambdaQueryWrapper<BloodSugarUserPermissionDepartment> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(BloodSugarUserPermissionDepartment::getDepartmentId,id);
            boolean remove = bloodSugarUserPermissionDepartmentService.remove(wrapper);
            if (remove) {
                return Result.ok();
            }else {
                return Result.error().code(R_Code.R_DELETE_FAIL);
            }
        } else {
            return Result.error().code(R_Code.R_DELETE_FAIL);
        }
    }

    @ApiOperation(value = "pc根据权限查询科室所有科室")
    @PreAuthorize("hasAnyAuthority('sys:departmentManage','sys:noAccess')")
    @GetMapping("getDepartmentByPerId/{perId}/{currentLoginUserId}/{deanId}")
    public Result getDepartmentByPerId(@ApiParam(name = "currentLoginUserId", value = "当前登录用户id") @NotNull(message = "当前登录用户id不能为空") @PathVariable Integer currentLoginUserId,
            @ApiParam(name = "perId", value = "权限id") @NotNull(message = "权限id不能为空") @PathVariable Integer perId,
            @ApiParam(name = "deanId", value = "院长id") @NotNull(message = "院长id不能为空") @PathVariable Integer deanId) {
        List<BloodSugarDepartment> departmentByPerId = bloodSugarDepartmentService.getDepartmentByPerId(perId, deanId ,currentLoginUserId);
        departmentByPerId.forEach(department -> {
            LambdaQueryWrapper<BloodSugarDoctor> departmentLambdaQueryWrapper = Wrappers.lambdaQuery();
            departmentLambdaQueryWrapper.eq(BloodSugarDoctor::getDepartmentId, department.getId());
            List<BloodSugarDoctor> list = bloodSugarDoctorService.list(departmentLambdaQueryWrapper);
            if (CollectionUtils.isNotEmpty(list)) {
                department.setIsHaveBloodSugarDoctorList(true);
                department.setBloodSugarDoctorList(list);
            } else {
                department.setIsHaveBloodSugarDoctorList(false);
                ArrayList<BloodSugarDoctor> arrayList = new ArrayList<>();
                arrayList.add(new BloodSugarDoctor());
                department.setBloodSugarDoctorList(arrayList);
            }
        });
        if (CollectionUtil.isNotEmpty(departmentByPerId)) {
            return Result.ok().data(departmentByPerId);
        } else {
            return Result.error().code(R_Code.R_NULL_DATA_FAIL);
        }
    }

}

